
//  ComposeViewController.swift
//  Weibo
//
//  Created by apple on 15/12/19.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
import SVProgressHUD

///撰写微博控制器
class ComposeViewController: UIViewController {
    ///照片选择控制器
    private lazy var picturePickerController = PicturePickerController()
    
    ///表情键盘试图
    ///有self 存在循环引用的问题  加上[weak self]
    private lazy var emoticonView: EmoticonView = EmoticonView {[weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
    }

    
    //MARK: 监听方法
    ///关闭
    @objc private func close() {
        ///关闭键盘
      textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    ///发布微博
    @objc private func sendStatus() {
    
//        dismissViewControllerAnimated(true, completion: nil)
        //1 获取文本内容
        let text = textView.emoticonText
        
        //2 发布微博
        let image = picturePickerController.pictursCount.last
        NetwokeTools.sharedTools.sendStatus(text, image: image) { (result, error) -> () in
            if error != nil {
            
                print("出错了")
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
            
            print(result)
            
            //关闭控制器
            self.close()
        }
        
    }
    ///选择照片
   @objc private func selectPicture() {
        print("选择照片\(picturePickerController.view.frame)")
        //退出键盘 
        textView.resignFirstResponder()

        //0 判断如果已经更新了约束  就不在执行后续代码
        if picturePickerController.view.frame.height < 0  {
        
            return
        }

        //1 修改照片选择控制器试图的约束
       picturePickerController.view.snp_updateConstraints { (make) -> Void in
        make.height.equalTo(view.bounds.height * 0.6)
    }
        // 2 修改文本试图的约束 重建约束 会将之前的textView的所有的约束删除
    textView.snp_remakeConstraints { (make) -> Void in
        make.top.equalTo(self.snp_topLayoutGuideBottom)
        make.left.equalTo(view.snp_left)
        make.right.equalTo(view.snp_right)
        make.bottom.equalTo(picturePickerController.view.snp_top)
    }

    // 3. 动画更新约束
    UIView.animateWithDuration(0.5) { () -> Void in
        self.view.layoutIfNeeded()
    }
    
}
    
    ///选择表情
    @objc private func selectEmoticon() {
    
        print("选择表情")
        // 1 退出键盘
        textView.resignFirstResponder()
        
        //2 设置键盘
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        //3 重新激活键盘
        textView.becomeFirstResponder()
        
    }
    ///键盘处理
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "keyboardChanged:",
            name: UIKeyboardWillChangeFrameNotification,
            object: nil)
        
    }
    deinit {
    //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    ///键盘变化监听方法
    @objc private func keyboardChanged(n: NSNotification) {
    
        print(n)
        // 1. 获取目标的 rect - 字典中的`结构体`是 NSValue

        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 获取目标的动画时长 - 字典中的数值是 NSNumber

//        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //动画曲线数值
        let cure = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -view.bounds.height + rect.origin.y
        // 2 更新约束
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
    
        }
        //动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: cure)!)
            self.view.layoutIfNeeded()
        }
        //MARK: 调试动画时长  
        let anim = toolbar.layer.animationForKey("position")
        print("动画时长\(anim?.duration)")
        
    }
    //MARK: 懒加载控件
    ///工具条
    private lazy var toolbar = UIToolbar()
    ///文本试图
    private lazy var textView: UITextView = {
    
        let vc = UITextView()
        vc.font = UIFont.systemFontOfSize(18)
        vc.textColor = UIColor.darkGrayColor()
        
        //允许垂直滚动
        vc.alwaysBounceVertical = true
        
        //拖动关闭键盘
        vc.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        //设置文本试图的代理
        vc.delegate = self
        
        return vc
    }()
    ///占位标签
    private lazy var placeHoderLabel = UILabel(title: "分享新鲜事...",
        fontSize: 18,
        color: UIColor.lightGrayColor())
    


    ///视图的生命周期
   override func loadView() {
    view = UIView()
    
    setupUI()
    
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        //激活键盘  如果已经存在照片控制器试图  不再激活键盘
//        if picturePickerController.view.frame.height == 0 {
//        }
        
        textView.becomeFirstResponder()
    }

}

///MARK: 设置界面
private extension ComposeViewController {
    //设置界面
    func setupUI(){
        //0 取消自动调整滚动试图间距
        automaticallyAdjustsScrollViewInsets = false
        //1 设置背景颜色
     view.backgroundColor = UIColor.whiteColor()
        
        prepareNavigationBar()
        prepareToolBar()
         prepareTextView()
        preparePicturePicker()

    }
   
    ///准备照片选择控制器
    private func preparePicturePicker() {
        //0 添加子控制器 UIView继承自UIResponsder
         addChildViewController(picturePickerController)
        
        //1 添加试图
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        
        //2 设置自动布局
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(view.snp_height).multipliedBy(0.6)
        }
        
        
    }
    ///准备文本视图
    private func prepareTextView() {
    
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        //占位标签
        textView.addSubview(placeHoderLabel)
        placeHoderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_top).offset(-60)
        }
        
    }
    ///准备工具条
    private func prepareToolBar() {
     
        ///添加工具条
        view.addSubview(toolbar)
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        //自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        //设置内容
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
        
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
    }
    ///MARK: 设置导航栏
    private func prepareNavigationBar() {
        
        //设置导航按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消",
            style: .Plain,
            target: self,
            action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送",
            style: .Plain,
            target: self,
            action: "sendStatus")
        //按钮禁用
        navigationItem.rightBarButtonItem?.enabled = false
        //设置导航试图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        navigationItem.titleView = titleView
        //标签
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(
            title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "",
            fontSize: 13,
            color: UIColor.lightGrayColor())
        print(nameLabel)
        //添加标签
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        //自动布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}

//MARK: UITextViewDelegate
extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem!.enabled = textView.hasText()
        placeHoderLabel.hidden = textView.hasText()
}
}
